import Log from '../tools/BELog';
import { getChain } from '../utils/be_chain';
import { isFunction } from '../utils/util';

// 执行函数队列
export function execAry(vm, execList) {
  if (execList && execList.length <= 0) {
    return;
  }
  return execList.reduce(
    function (prev, item) {
      if (isFunction(item)) {
        item.call(prev);
      }

      if (typeof item === 'string' && isFunction(prev[item])) {
        prev[item]();
      }

      return prev;
    },
    vm
  );
}

// 执行异步预定义函数队列
export function execAsyncList(vm, asyncList) {
  const list = asyncList.execList.map(function(item) {
    if (isFunction(item)) {
      return item;
    }
    if (typeof item === 'string' && isFunction(vm[item])) {
      return vm[item];
    }
  });
  let chain = getChain(
    list,
    function(err, ...args) {
      if (err) {
        Log.error('exec async init execList failed:', err);
      }

      chain.destroy();
      chain = null;

      const cb = asyncList.complete;

      // asyncList.destroy();
      asyncList = null;

      if (typeof cb === 'function') {
        cb.apply(vm, [err, ...args]);
      }
    },
    vm
  );

  chain.next();
}
